//
//  AddAddressViewController.m
//  SXH
//
//  Created by Jack on 15/9/15.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "AddAddressViewController.h"
#import "DYCAddress.h"
#import "DYCAddressPickerView.h"
#import "Address.h"
#import "UserAddressEntity.h"
#import "CommonService.h"

@interface AddAddressViewController ()<DYCAddressDelegate,DYCAddressPickerViewDelegate,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UILabel *viewTitle;
@property (strong,nonatomic) UIView *addressPicker;
@property (weak, nonatomic) IBOutlet UITextField *addName;
@property (weak, nonatomic) IBOutlet UITextField *addPhone;
@property (weak, nonatomic) IBOutlet UITextField *baseAddress;
@property (weak, nonatomic) IBOutlet UIButton *baseAddressBtn;
@property (weak, nonatomic) IBOutlet UITextField *detailAddress;
@property (weak,nonatomic) IBOutlet UIButton *btnIsDefault;
@property (weak,nonatomic) IBOutlet UIButton *btnEnsure;
@property (weak,nonatomic) IBOutlet UIButton *btnDel;
@property BOOL addOrEdit;

@property NSString *pro_name;
@property NSString *city_name;
@property NSString *district;

@end

@implementation AddAddressViewController
@synthesize addressPicker;
@synthesize addName,addPhone,baseAddress,detailAddress;
@synthesize btnEnsure,btnIsDefault;
@synthesize addressView,orderEnsureView;
@synthesize userAddressEntity;
@synthesize cellIndex;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    addName.delegate = self;
    addPhone.delegate = self;
    baseAddress.delegate = self;
    detailAddress.delegate = self;
    
    //确认地址边框
    btnEnsure.layer.cornerRadius = 5.0f; //圆角半径
    btnEnsure.layer.masksToBounds = YES; //圆角
    btnEnsure.layer.borderWidth = 0.5f; //边框宽度
    btnEnsure.layer.borderColor = [[UIColor grayColor]CGColor]; //边框颜色
    
    //初始化 UITextField 控件
    addName.text = userAddressEntity.addName;
    addPhone.text = userAddressEntity.addPhone;
    detailAddress.text = userAddressEntity.detailAddress;
    btnIsDefault.selected = [userAddressEntity.isDefault isEqualToString:@"1"]?true:false;
    [btnIsDefault setImage:[UIImage imageNamed:K_trade_default_imageName] forState:UIControlStateNormal];
    [btnIsDefault setImage:[UIImage imageNamed:K_trade_OK_imageName] forState:UIControlStateSelected];
    if([addName.text isEqualToString:@""]){
        _addOrEdit = YES;
        _btnDel.hidden = YES;
    }else{
        _viewTitle.text = @"编辑地址";
        _addOrEdit = NO;
        _pro_name = userAddressEntity.pro_name;
        _city_name = userAddressEntity.city_name;
        _district = userAddressEntity.district;
        baseAddress.text = [NSString stringWithFormat:@"%@%@%@",userAddressEntity.pro_name,userAddressEntity.city_name,userAddressEntity.district];
        _btnDel.hidden = NO;
    }
    
    addressPicker = [[UIView alloc]initWithFrame:CGRectMake(0,SCREEN_HEIGHT,SCREEN_WIDTH,180)];
    [self.view addSubview:addressPicker];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    DYCAddress *address = [[DYCAddress alloc] init];
    address.dataDelegate = self;
    [address handlerAddress];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(void)addressList:(NSArray *)array
{
    DYCAddressPickerView *pickerView = [[DYCAddressPickerView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 180) withAddressArray:array];
    pickerView.DYCDelegate = self;
    pickerView.backgroundColor = [UIColor whiteColor];
    [self.addressPicker addSubview:pickerView];
}
-(void)selectAddressProvince:(Address *)province andCity:(Address *)city andCounty:(Address *)county
{
    _pro_name=province.name;
    _city_name=city.name;
    _district=county.name;
    baseAddress.text = [NSString stringWithFormat:@"%@%@%@", province.name,city.name,county.name];
}

//点击空白隐藏键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
    [self inView];
}

- (void)popView {
//    self.addressPicker.hidden = false;
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.6];//动画时间长度，单位秒，浮点数
    [self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
    self.addressPicker.frame = CGRectMake(0, 380, SCREEN_WIDTH, 180);
    
    [UIView setAnimationDelegate:self];
    // 动画完毕后调用animationFinished
    [UIView setAnimationDidStopSelector:@selector(animationFinished)];
    [UIView commitAnimations];
}

- (void)inView {
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.6];//动画时间长度，单位秒，浮点数
    self.addressPicker.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 180);
    
    [UIView setAnimationDelegate:self];
    // 动画完毕后调用animationFinished
    [UIView setAnimationDidStopSelector:@selector(animationFinished)];
    [UIView commitAnimations];
}
-(void)animationFinished{
    NSLog(@"动画结束!");
}

-(IBAction)baseAddressBtn:(id)sender{
    [self.view endEditing:YES];
    [self popView];
}

-(IBAction)btnIsDefault:(id)sender{
    btnIsDefault.selected = !btnIsDefault.selected;
    [btnIsDefault setImage:[UIImage imageNamed:K_trade_default_imageName] forState:UIControlStateNormal];
    [btnIsDefault setImage:[UIImage imageNamed:K_trade_OK_imageName] forState:UIControlStateSelected];
}

-(IBAction)postAddress:(id)sender{
    if(![self validateMobile:addPhone.text]){
        ALERT_ERR_MSG(@"请填写真确的手机号!");
        return;
    }
    if([addName.text isEqualToString:@""]
       ||[addPhone.text isEqualToString:@""]
       ||[_pro_name isEqualToString:@""]
       ||[detailAddress.text isEqualToString:@""]){
        ALERT_ERR_MSG(@"收件人、手机号、地址不能为空!");
        return;
    }
    
    UserEntity *userEntity = [UserEntity sharedInstance];
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           userEntity.userId, @"userid",
                           addName.text, @"nickname",
                           addPhone.text, @"phone",
                           _pro_name, @"pro_name",
                           _city_name, @"city_name",
                           _district, @"district",
                           detailAddress.text, @"address_info",
                           ((btnIsDefault.selected)?@"1":@"0"), @"def",
                           userAddressEntity.ID,@"id",
                           nil];
    if(_addOrEdit)
    [service getNetWorkData:param
                       Path:USER_ADDRESS_POST
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSNumber *code = (NSNumber*)[dic objectForKey:@"code"];
                      dispatch_async(dispatch_get_main_queue(), ^{
                          if([code intValue] == 0){
                              orderEnsureView.userEntity = userEntity;
                              [orderEnsureView viewDidLoad];
                              [addressView viewDidLoad];
                              //返回上一页
                              [self.navigationController popViewControllerAnimated:YES];
                          }
                      });
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                  }];
    else
        [service getNetWorkData:param
                           Path:USER_ADDRESS_UPDATE
                      Successed:^(id entity) {
                          NSDictionary *dic = (NSDictionary *)entity;
                          NSNumber *code = (NSNumber*)[dic objectForKey:@"code"];
                          dispatch_async(dispatch_get_main_queue(), ^{
                              if([code intValue] == 0){
                                  [addressView viewDidLoad];
                                  //返回上一页
                                  [self.navigationController popViewControllerAnimated:YES];
                              }
                          });
                          
                      } Failed:^(NSInteger errorCode, NSString *message) {
                          DebugLog(@"%@", message);
                      }];
    
}

- (BOOL)validateMobile:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}


-(IBAction)postAddress_origin:(id)sender{
    UserAddressEntity *newAddressEntity = [[UserAddressEntity alloc]init];
    newAddressEntity.addName = addName.text;
    newAddressEntity.addPhone = addPhone.text;
    newAddressEntity.baseAddress = baseAddress.text;
    newAddressEntity.detailAddress = detailAddress.text;
    //    newAddressEntity.isDefault = (btnIsDefault.selected)?true:false;
    newAddressEntity.isDefault = (btnIsDefault.selected)?@"1":@"0";
    
    NSUserDefaults *address = [NSUserDefaults standardUserDefaults];
    //可以用alloc 方法代替
    NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:[address objectForKey:@"AddressArray"]];
    //改变默认地址
    if(newAddressEntity.isDefault){
        for (int i=0;i<[mutableArray count]; i++) {
            UserAddressEntity *addressEntity = [NSKeyedUnarchiver unarchiveObjectWithData:[mutableArray objectAtIndex:i]];
            if(!addressEntity.isDefault)
                continue;
            addressEntity.isDefault = @"0";
            NSData *newData = [NSKeyedArchiver archivedDataWithRootObject:addressEntity];
            [mutableArray replaceObjectAtIndex:i withObject:newData];
        }
    }
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:newAddressEntity];
    if(_addOrEdit)
        //存放数据的数组将data加入进去
        [mutableArray addObject:data];
    else
        [mutableArray replaceObjectAtIndex:cellIndex withObject:data];
    //记住要转换成不可变数组类型
    NSArray * array = [NSArray arrayWithArray:mutableArray];
    [address setObject:array forKey:@"AddressArray"];
    
    [addressView viewDidLoad];
    //返回上一页
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"AddAddressViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"AddAddressViewController"];
}

-(IBAction)btnDelAction:(id)sender{
    UserEntity *userEntity = [UserEntity sharedInstance];
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           userAddressEntity.ID,@"id",userEntity.userId, @"userid",nil];
    [service getNetWorkData:param
                       Path:USER_ADDRESS_DELETE
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSString *code = [dic objectForKey:@"code"];
                      dispatch_async(dispatch_get_main_queue(), ^{
                          if([code intValue]==0){
                              [addressView viewDidLoad];
                              [self.navigationController popViewControllerAnimated:YES];
                          }
                      });
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                  }];
}
@end
